package com.sjd.controller;

import ch.qos.logback.core.util.IncompatibleClassException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyController {
    @RequestMapping({"/","/index"})
    public  String toindex(Model model){
        model.addAttribute("msg","helloshrio");
        return "index";
    }
    @RequestMapping("/user/add")
    public String toadd(){
        return "/user/add";
    }
    @RequestMapping("/user/update")
    public String toupdate(){
        return "/user/update";
    }
    @RequestMapping("/tologin")
    public String toLogin(){
        return "login";
    }
    @RequestMapping("/login")
    public String login(String name,String password,Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(name, password);
        try {
            subject.login(token);//执行登录方法，如果没有异常就说明ok
            return "redirect:/index";
        }catch (UnknownAccountException exception){//用户名不存在或者错误
            model.addAttribute("msg","用户名错误");
            return "login";
        }catch (IncorrectCredentialsException e){//密码不存在或者错误
            model.addAttribute("msg","密码错误");
            return "login";

        }

    }

    @RequestMapping("/noauth")//未授权页面
    public String unauthorized(){

        return "/error/401";
    }
}
